'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
var ExtractTextPlugin = require("extract-text-webpack-plugin")// 提取css的插件

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '智能白蚁检测平台' // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following method:
// port = 9527 npm run serve OR npm run serve --port = 9527
const port = process.env.port || process.env.npm_config_port || 9527 // serve port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: false, //process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    // overlay: {
    //   warnings: false,
    //   errors: true
    // },
    // before: require('./mock/mock-server.js'),
    proxy: {
      "/xiaoyi": {
        // target: "http://39.108.224.94:80",
        // target: "http://cps.tiegang.wang",
        // target: "http://47.102.110.85:80",
        target: "http://service.xiaoyiyunlian.com",
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          '': ''
        },
        onProxyReq(proxyReq, req, res) {
          console.log("原路径：" + req.originalUrl, "代理路径：" + req.path)
        }
      }
    },
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src'),
      }
    },
    externals:{
      'BMapGL': 'BMapGL',  // 外部链接 减少打包组件
      fs: require('fs'),
      // "path": require.resolve("path-browserify"),
      // "path": require.resolve("path-to-regexp"),
      
    },
    // plugins: [
    //   new ExtractTextPlugin({
    //     filename: 'css/[name].[contenthash:8].css',
    //     chunkFilename: 'css/[name].[contenthash:8].css'
    //   })
    // ]
    
     
  },
  chainWebpack(config) {

    if (process.env.use_analyzer) {     // 分析
      config
        .plugin('webpack-bundle-analyzer')
        .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    }

    // it can improve the speed of the first screen, it is recommended to turn on preload
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').use(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/serve/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')
    // 移除 preload 插件，避免加载多余的资源
    config.plugins.delete('preload');

    // if (process.env.NODE_ENV === 'production') {
    //   // 删除原来的style loader
    //   config.module
    //     .rule('css')
    //     .delete('style');
 
    //   // 添加ExtractTextPlugin为生产模式
    //   config.plugin('extract-css').use(ExtractTextPlugin, [{
    //     filename: 'css/[name].[contenthash:8].css',
    //     chunkFilename: 'css/[name].[contenthash:8].css'
    //   }]);
    // }
    

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {

        // config.module
        //   .rule('css')
        //   .test(/\.css$/)
        //   .use('css-loader')
        //     .loader('css-loader')
        //     .options({
        //       // 可以在这里配置css-loader的选项
        //     })

          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')

           
           // 解决ie11兼容ES6
          config.entry('main').add('babel-polyfill')


          // config.module.rule("images")
          // .use('url-loader')
          // .loader('url-loader')
          // .tap(options => ({ ...options, limit: 6144 }) )

          // config.module
          // .rule('images')
          // .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
          // .use('file-loader')
          // .loader('file-loader')
          // .options({
          // name: '[name].[hash:8].[ext]',
          // })



          // config.module
          // .rule('scss')
          // .oneOf('vue')
          // .use('sass-loader')
          // .tap(options => {
          //   // options.additionalData = `@import "@/styles/variables.module.scss";`;
          //   return options;
          // });



        }
      )
  },
  css: {
    extract: true,
    loaderOptions: {
      sass: {
        // 这里是SCSS的加载器配置
      },
    },
    sourceMap: false
  }
}
